﻿using BCL.BaseLib.Basics;
using BCL.Tool.BCLThreading;
using System;
using System.IO;
using BCL.Tool;
using System.Text;

namespace DevicesView.Logic.Log
{
    public class BCLLog : ILog
    {
        private string LogPath;
        private string MsgPath;
        private string ErrorPath;
        private string httpPath;
        private static byte[] Enter;
        private static byte[] Dividing;
        private static object LockObj=1;
        // private BlockingCollection<byte[]> blockingCollection;
        /// <summary>
        /// log文件读写线程,所有的log文件读写在此线程中运行
        /// </summary>
        //private BCL.Tool.BCLThreading.BCLThread thread;
        public BCLLog()
        {
            LogPath = AppDomain.CurrentDomain.BaseDirectory + "log\\" + DateTime.Now.ToString("yyyyMM") + "\\";
            if (!Directory.Exists(LogPath))
                Directory.CreateDirectory(LogPath);
            MsgPath = LogPath + DateTime.Now.ToString("dd") + "_msg.txt";
            ErrorPath = LogPath + DateTime.Now.ToString("dd") + "_error.txt";
            httpPath = LogPath + DateTime.Now.ToString("dd") + "_http.txt";


            Dividing = System.Text.UTF8Encoding.UTF8.GetBytes("----------------------------------------\r\n");
            Enter = System.Text.UTF8Encoding.UTF8.GetBytes("\r\n\r\n");
            //thread = new BCLThread();
            //System.Windows.Forms.Application.ApplicationExit += (s, o) => Exit();

        }
        public void Error(string text, Exception ex)
        {
            Error(text +"\r\n"+ ex.StackTrace+"\r\n");
        }

        public void Error(Exception ex)
        {
            Error(ex.Message, ex);
        }

        public void Error(string text)
        {
            WriteLog(ErrorPath, text);// System.Text.UTF8Encoding.UTF8.GetBytes(text)) ;
        }

        public void Msg(string text)
        {
            WriteLog(MsgPath, text);// System.Text.UTF8Encoding.UTF8.GetBytes(text));
        }

        public void http(HttpItem item)
        {
            StringBuilder sb = new StringBuilder("\r\nRequest\r\n--->\r\n");
            sb.Append(item.Url+"\r\n");
            sb.Append(item.Method+"\r\n");
            if(item.Content!=null)
            sb.Append(UTF8Encoding.UTF8.GetString(item.Content));
            sb.Append("\r\n\r\n");
            WriteLog(httpPath,sb.ToString());
        }
        public void http(string text)
        {
            StringBuilder sb = new StringBuilder("\r\nResponse\r\n--->\r\n");
            sb.Append(text + "\r\n");
            sb.Append("\r\n");
            WriteLog(httpPath, sb.ToString());
        }

        public void Write(string text)
        {
            Msg(text);
        }

        


        public void Write(string text, string titel)
        {
            Msg(titel + ":\r\n" + text);
        }

        public void Write(string text, string titel, LogType logType)
        {
            switch (logType)
            {
                case LogType.Error:
                    Error(titel + ":\r\n" + text);
                    break;
                case LogType.Msg:
                    Msg(titel + ":\r\n" + text);
                    break;
            }
        }
        public void Write(string text, string appid, OperationType otype)
        {

        }
        private void WriteLog(string path, byte[] data)
        {
            //将写件操作添加到队列
            System.Threading.ThreadPool.QueueUserWorkItem(o =>
            {
                lock (LockObj)
                {
                    string title = DateTime.Now.ToString("HH:mm:ss");
                    byte[] titlebuffer = System.Text.UTF8Encoding.UTF8.GetBytes(title);
                    using (FileStream fs = File.Open(path, FileMode.OpenOrCreate))
                    {
                        fs.Position = fs.Length;

                        fs.Write(titlebuffer, 0, titlebuffer.Length);
                        fs.Write(Dividing, 0, Dividing.Length);
                        fs.Write(data, 0, data.Length);
                        fs.Write(Enter, 0, Enter.Length);
                    }
                }
            });
        }

        private void WriteLog(string path, string str)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(o =>
            {
                lock (LockObj)
                {
                    string title = DateTime.Now.ToString("HH:mm:ss");
                    File.AppendAllText(path,title+str,System.Text.Encoding.UTF8);
                }
            });
        }
        public string Read(LogType logType = LogType.Error)
        {
            string logpath = ErrorPath;
            if (logType == LogType.Msg)
                logpath = MsgPath;
            if (File.Exists(logpath))
            {
                try
                {
                    return File.ReadAllText(logpath, System.Text.UTF8Encoding.UTF8);
                }
                finally
                {

                }
            }
            return null;
        }

        private void Exit()
        {
            //thread.Exit();
        }


    }
}
